all repos — caroster @ 512757d6ae90dfc3ddae08bb34ddb889ee3ec54f

[Octree] Group carpool to your event https://caroster.io

frontend/pages/api/nauth/[...nextauth].js (view raw)

 1import NextAuth from 'next-auth';
 2import CredentialsProvider from 'next-auth/providers/credentials';
 3import GoogleProvider from 'next-auth/providers/google';
 4
 5const {STRAPI_URL = 'http://localhost:1337'} = process.env;
 6
 7export default NextAuth({
 8  providers: [
 9    CredentialsProvider({
10      name: 'Strapi',
11      credentials: {
12        email: {label: 'Email', type: 'text'},
13        password: {label: 'Password', type: 'password'},
14      },
15      async authorize(credentials, req) {
16        const response = await fetch(`${STRAPI_URL}/api/auth/local`, {
17          method: 'POST',
18          headers: {'Content-Type': 'application/json'},
19          body: JSON.stringify({
20            identifier: credentials.email,
21            password: credentials.password,
22          }),
23        });
24        const data = await response.json();
25        if (data?.error?.message === 'Your account email is not confirmed')
26          throw new Error('EmailNotConfirmed');
27        else if (!data?.jwt) return null;
28        const {user, jwt} = data;
29        return {...user, jwt};
30      },
31    }),
32    GoogleProvider({
33      clientId: process.env.GOOGLE_CLIENT_ID,
34      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
35    }),
36  ],
37  session: {
38    jwt: true,
39  },
40  callbacks: {
41    jwt: async params => {
42      const {token, user, account} = params;
43
44      // Google Auth
45      if (account?.provider === 'google') {
46        const strapiUrl = process.env.STRAPI_URL || 'http://localhost:1337';
47        const response = await fetch(
48          `${strapiUrl}/api/auth/${account.provider}/callback?access_token=${account?.access_token}`
49        );
50        const data = await response.json();
51        token.id = data.user.id;
52        token.jwt = data.jwt;
53        token.email = data.user.email;
54        token.username = data.user.firstname;
55        token.lang = data.user.lang?.toLowerCase();
56      }
57
58      // Strapi Auth
59      else if (user) {
60        token.id = user.id;
61        token.jwt = user.jwt;
62        token.email = user.email;
63        token.username = user.firstname;
64        token.lang = user.lang?.toLowerCase();
65      }
66
67      return token;
68    },
69    session: async params => {
70      const {session, token} = params;
71      if (session) {
72        session.token = token;
73        session.user.name = token.username;
74        session.user.lang = token.lang;
75      }
76      return session;
77    },
78  },
79  pages: {
80    signIn: '/auth/login',
81    error: '/auth/login',
82  },
83});